import logging
from logging.handlers import TimedRotatingFileHandler


def setup_logger():
    # 创建主记录器
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)  # 设置最低级别

    # 避免重复添加处理器
    if logger.hasHandlers():
        logger.handlers.clear()

    # 1. 文件处理器（按天分割）
    file_handler = TimedRotatingFileHandler(
        "./log/app.log", when="midnight", backupCount=7, encoding="utf-8"
    )
    file_handler.setLevel(logging.DEBUG)
    file_formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - [%(name)s]:[%(filename)s - %(lineno)d] - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    file_handler.setFormatter(file_formatter)

    # 2. 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_formatter = logging.Formatter(
        "[%(levelname)-8s] %(name)s: %(message)s"
    )
    console_handler.setFormatter(console_formatter)

    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger

# 初始化主记录器
app_logger = setup_logger()